<template>
  <div class="indicator-wrap">
    <div v-if="showTitle" class="indicator-title">
      {{ tabs[curIndex] }}
    </div>
    <div
      v-for="(item, idx) in tabs"
      :key="item"
      ref="indicator"
      :class="{'indicator-item':true,'indicator-item-active':curIndex === idx}"
      :style="{width:itemWidth+'px','background-color':getTabColor(idx)}"
      @click="changeTab(idx)"
    />
  </div>
</template>

<script>
export default {
  name: 'HzxIndicator',
  props: {
    index: {
      type: Number,
      default: () => 0
    },
    tabs: {
      type: Array,
      default: () => ['演示一', '演示二', '演示三']
    },
    tabColor: {
      type: String,
      default: () => 'rgb(51,59,72)'
    },
    tabActiveColor: {
      type: Array,
      default: () => ['red', '#27C492', '#F79A56']
    },
    showTitle: {
      type: Boolean,
      default: () => true
    },
    dur: {
      type: Number,
      default: () => 2000
    }
  },
  data() {
    return {
      itemWidth: '',
      curIndex: 0,
      interval: ''
    }
  },
  computed: {
    getTabColor() {
      return (i) => {
        const colors = this.tabActiveColor
        const color = i === this.curIndex ? colors[i] : this.tabColor
        return color
      }
    }
  },
  mounted() {
    this.curIndex = this.index
    this.itemWidth = this.$refs['indicator'][0].offsetHeight + 2
    // in case father dom no height attribute
    this.itemWidth === 2 && setTimeout(() => {
      this.itemWidth = this.$refs['indicator'][0].offsetHeight + 2
    }, 100)
    this.play()
  },

  methods: {
    changeTab(index) {
      this.curIndex = index
      this.$emit('changeTab', index)
      this.play()
    },
    play() {
      this.interval && clearInterval(this.interval)
      this.interval = setInterval(() => {
        this.curIndex = this.curIndex === this.tabs.length - 1 ? 0 : this.curIndex + 1
        this.changeTab(this.curIndex)
      }, this.dur)
    }
  }
}
</script>

<style lang="less" scoped="scoped">
  .indicator-wrap{
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-around;
    align-items: center;
    .indicator-title{
        margin-right: 10px;
    }
    .indicator-item{
      height: 60%;
      margin: 0 5px;
    }
    .indicator-item:hover{
      cursor: pointer;
    }
    .indicator-item-active{
      background-color: yellow;
    }
  }
</style>
